/**
 * 组件解耦初始化器
 * 管理组件系统从强耦合向事件驱动架构的迁移
 */

import { ComponentEventBus } from './ComponentEventBus';
import { COMPONENT_EVENTS } from './ComponentEvents';
import { ServiceLogger } from '../logging/UnifiedLogger';
import { createServiceErrorHandler } from '../error/ErrorHandlingInitializer';

/**
 * 组件解耦配置
 */
export interface ComponentDecouplingConfig {
    /** 是否启用事件总线 */
    enableEventBus?: boolean;
    /** 是否启用兼容模式（新旧组件并存） */
    enableCompatibilityMode?: boolean;
    /** 事件总线配置 */
    eventBus?: {
        /** 最大事件历史记录数 */
        maxHistorySize?: number;
        /** 是否启用事件统计 */
        enableMetrics?: boolean;
        /** 调试模式 */
        debugMode?: boolean;
    };
    /** 迁移配置 */
    migration?: {
        /** 自动迁移组件列表 */
        autoMigrateComponents?: string[];
        /** 迁移策略 */
        strategy?: 'gradual' | 'immediate';
        /** 是否启用回滚 */
        enableRollback?: boolean;
    };
}

/**
 * 组件解耦状态
 */
interface DecouplingStatus {
    initialized: boolean;
    eventBusEnabled: boolean;
    migratedComponents: string[];
    compatibilityMode: boolean;
    eventMetrics: any;
}

/**
 * 组件解耦管理器
 */
export class ComponentDecouplingManager {
    private static instance: ComponentDecouplingManager;
    private eventBus: ComponentEventBus;
    private logger: ServiceLogger;
    private errorHandler: any;
    private config: ComponentDecouplingConfig;
    private status: DecouplingStatus;
    private isInitialized = false;

    private constructor() {
        this.logger = new ServiceLogger('ComponentDecouplingManager');
        this.errorHandler = createServiceErrorHandler('ComponentDecouplingManager');
        this.eventBus = ComponentEventBus.getInstance();
        this.status = {
            initialized: false,
            eventBusEnabled: false,
            migratedComponents: [],
            compatibilityMode: false,
            eventMetrics: null
        };
    }

    /**
     * 获取单例实例
     */
    static getInstance(): ComponentDecouplingManager {
        if (!this.instance) {
            this.instance = new ComponentDecouplingManager();
        }
        return this.instance;
    }

    /**
     * 初始化组件解耦系统
     */
    async initialize(config: ComponentDecouplingConfig = {}): Promise<void> {
        if (this.isInitialized) {
            this.logger.warn('Component decoupling system already initialized');
            return;
        }

        this.logger.info('🔗 Initializing Component Decoupling System...');

        try {
            // 合并配置
            this.config = this.mergeConfig(config);
            
            // 第一步：初始化事件总线
            await this.initializeEventBus();
            
            // 第二步：设置核心事件监听器
            await this.setupCoreEventListeners();
            
            // 第三步：启用兼容模式（如果需要）
            if (this.config.enableCompatibilityMode) {
                await this.enableCompatibilityMode();
            }
            
            // 第四步：执行自动迁移（如果配置）
            if (this.config.migration?.autoMigrateComponents) {
                await this.performAutoMigration();
            }
            
            this.status.initialized = true;
            this.isInitialized = true;
            
            this.logger.info('✅ Component decoupling system initialized successfully', {
                metadata: { 
                    eventBusEnabled: this.status.eventBusEnabled,
                    compatibilityMode: this.status.compatibilityMode,
                    migratedComponents: this.status.migratedComponents.length
                }
            });

        } catch (error) {
            const gameError = this.errorHandler.handleError(error, 'initialize');
            this.logger.error('❌ Failed to initialize component decoupling system', gameError);
            throw gameError;
        }
    }

    /**
     * 合并配置
     */
    private mergeConfig(userConfig: ComponentDecouplingConfig): ComponentDecouplingConfig {
        const defaultConfig: ComponentDecouplingConfig = {
            enableEventBus: true,
            enableCompatibilityMode: true,
            eventBus: {
                maxHistorySize: 1000,
                enableMetrics: true,
                debugMode: process.env.NODE_ENV !== 'production'
            },
            migration: {
                autoMigrateComponents: [],
                strategy: 'gradual',
                enableRollback: true
            }
        };

        return {
            enableEventBus: userConfig.enableEventBus ?? defaultConfig.enableEventBus,
            enableCompatibilityMode: userConfig.enableCompatibilityMode ?? defaultConfig.enableCompatibilityMode,
            eventBus: { ...defaultConfig.eventBus, ...userConfig.eventBus },
            migration: { ...defaultConfig.migration, ...userConfig.migration }
        };
    }

    /**
     * 初始化事件总线
     */
    private async initializeEventBus(): Promise<void> {
        if (!this.config.enableEventBus) {
            this.logger.info('Event bus disabled by configuration');
            return;
        }

        // 配置事件总线
        this.eventBus.setEnabled(true);
        
        // 设置调试模式
        if (this.config.eventBus?.debugMode) {
            this.setupEventBusDebugging();
        }

        this.status.eventBusEnabled = true;
        this.logger.info('Event bus initialized and enabled');
    }

    /**
     * 设置事件总线调试
     */
    private setupEventBusDebugging(): void {
        // 监听所有事件类型进行调试
        const debugEventTypes = [
            ...Object.values(COMPONENT_EVENTS.EQUIPMENT),
            ...Object.values(COMPONENT_EVENTS.BAG),
            ...Object.values(COMPONENT_EVENTS.RPG),
            ...Object.values(COMPONENT_EVENTS.TALENT),
            ...Object.values(COMPONENT_EVENTS.FOLLOW),
            ...Object.values(COMPONENT_EVENTS.TASK),
            ...Object.values(COMPONENT_EVENTS.SIGN),
            ...Object.values(COMPONENT_EVENTS.SYSTEM)
        ];

        debugEventTypes.forEach(eventType => {
            this.eventBus.on(eventType, 'ComponentDecouplingManager', (event) => {
                this.logger.debug(`Event emitted: ${eventType}`, {
                    metadata: {
                        eventId: event.eventId,
                        source: event.source,
                        dataKeys: Object.keys(event.data || {})
                    }
                });
            }, { priority: 0 }); // 最低优先级，在所有业务处理器之后执行
        });

        this.logger.info('Event bus debugging enabled');
    }

    /**
     * 设置核心事件监听器
     */
    private async setupCoreEventListeners(): Promise<void> {
        // 监听系统错误事件
        this.eventBus.on(
            COMPONENT_EVENTS.SYSTEM.ERROR_OCCURRED,
            'ComponentDecouplingManager',
            (event) => this.handleSystemError(event),
            { priority: 100 } // 高优先级
        );

        // 监听组件销毁事件
        this.eventBus.on(
            COMPONENT_EVENTS.SYSTEM.COMPONENT_DESTROYED,
            'ComponentDecouplingManager',
            (event) => this.handleComponentDestroyed(event)
        );

        // 定期生成事件统计报告
        if (this.config.eventBus?.enableMetrics) {
            setInterval(() => {
                this.generateEventMetricsReport();
            }, 5 * 60 * 1000); // 每5分钟
        }

        this.logger.info('Core event listeners setup completed');
    }

    /**
     * 启用兼容模式
     */
    private async enableCompatibilityMode(): Promise<void> {
        this.logger.info('Enabling compatibility mode for component migration');

        // 设置兼容性事件桥接
        this.setupCompatibilityBridge();

        this.status.compatibilityMode = true;
        this.logger.info('Compatibility mode enabled');
    }

    /**
     * 设置兼容性桥接
     */
    private setupCompatibilityBridge(): void {
        // 为旧组件提供事件桥接
        // 当新组件发射事件时，如果有旧组件依赖，提供回调机制
        
        this.logger.debug('Setting up compatibility bridge for legacy components');
        
        // 这里可以添加具体的桥接逻辑
        // 例如：监听装备事件，然后调用旧的RPG组件更新方法
    }

    /**
     * 执行自动迁移
     */
    private async performAutoMigration(): Promise<void> {
        const componentsToMigrate = this.config.migration?.autoMigrateComponents || [];
        
        if (componentsToMigrate.length === 0) {
            this.logger.info('No components configured for auto migration');
            return;
        }

        this.logger.info('Starting auto migration of components', {
            metadata: { components: componentsToMigrate }
        });

        for (const componentName of componentsToMigrate) {
            try {
                await this.migrateComponent(componentName);
                this.status.migratedComponents.push(componentName);
                this.logger.info(`Component migrated successfully: ${componentName}`);
            } catch (error) {
                this.logger.error(`Failed to migrate component: ${componentName}`, error);
                
                if (!this.config.migration?.enableRollback) {
                    throw error;
                }
            }
        }

        this.logger.info('Auto migration completed', {
            metadata: { 
                migrated: this.status.migratedComponents.length,
                total: componentsToMigrate.length 
            }
        });
    }

    /**
     * 迁移单个组件
     */
    async migrateComponent(componentName: string): Promise<void> {
        this.logger.info(`Migrating component: ${componentName}`);
        
        // 这里实现具体的组件迁移逻辑
        // 1. 创建新的事件驱动组件实例
        // 2. 迁移数据
        // 3. 建立事件监听器
        // 4. 更新注册信息
        
        // 模拟迁移过程
        await new Promise(resolve => setTimeout(resolve, 100));
        
        this.logger.info(`Component migration completed: ${componentName}`);
    }

    /**
     * 处理系统错误事件
     */
    private handleSystemError(event: any): void {
        this.logger.error('System error event received', {
            metadata: {
                component: event.data.component,
                playerId: event.data.playerId,
                errorMessage: event.data.error?.message
            }
        });

        // 这里可以添加错误恢复逻辑
        // 例如：如果某个组件频繁出错，自动禁用事件或回滚到旧版本
    }

    /**
     * 处理组件销毁事件
     */
    private handleComponentDestroyed(event: any): void {
        this.logger.info('Component destroyed event received', {
            metadata: {
                component: event.data.component,
                playerId: event.data.playerId
            }
        });

        // 清理相关的事件监听器和状态
    }

    /**
     * 生成事件统计报告
     */
    private generateEventMetricsReport(): void {
        try {
            const metrics = this.eventBus.getMetrics();
            this.status.eventMetrics = metrics;

            if (metrics.totalEvents > 0) {
                this.logger.info('Event metrics report', {
                    metadata: {
                        totalEvents: metrics.totalEvents,
                        avgProcessingTime: metrics.avgProcessingTime,
                        errorCount: metrics.errorCount,
                        lastEventTime: new Date(metrics.lastEventTime).toISOString(),
                        topEventTypes: Array.from(metrics.eventsByType.entries())
                            .sort(([,a], [,b]) => b - a)
                            .slice(0, 5)
                            .map(([type, count]) => ({ type, count }))
                    }
                });

                // 如果错误率过高，发出警告
                if (metrics.errorCount / metrics.totalEvents > 0.1) {
                    this.logger.warn('High event error rate detected', {
                        metadata: { 
                            errorRate: ((metrics.errorCount / metrics.totalEvents) * 100).toFixed(2) + '%'
                        }
                    });
                }
            }
        } catch (error) {
            this.logger.error('Failed to generate event metrics report', error);
        }
    }

    /**
     * 获取解耦状态
     */
    getStatus(): DecouplingStatus {
        // 更新事件统计
        if (this.status.eventBusEnabled) {
            this.status.eventMetrics = this.eventBus.getMetrics();
        }
        
        return { ...this.status };
    }

    /**
     * 获取事件总线实例
     */
    getEventBus(): ComponentEventBus {
        return this.eventBus;
    }

    /**
     * 获取组件迁移状态
     */
    getMigrationStatus(): {
        strategy: string;
        migratedComponents: string[];
        totalComponents: number;
        compatibilityMode: boolean;
    } {
        return {
            strategy: this.config.migration?.strategy || 'gradual',
            migratedComponents: this.status.migratedComponents,
            totalComponents: this.config.migration?.autoMigrateComponents?.length || 0,
            compatibilityMode: this.status.compatibilityMode
        };
    }

    /**
     * 手动触发组件迁移
     */
    async triggerComponentMigration(componentName: string): Promise<void> {
        if (this.status.migratedComponents.includes(componentName)) {
            throw new Error(`Component ${componentName} is already migrated`);
        }

        await this.migrateComponent(componentName);
        this.status.migratedComponents.push(componentName);
        
        this.logger.info(`Component migration triggered manually: ${componentName}`);
    }

    /**
     * 回滚组件迁移
     */
    async rollbackComponentMigration(componentName: string): Promise<void> {
        const index = this.status.migratedComponents.indexOf(componentName);
        if (index === -1) {
            throw new Error(`Component ${componentName} is not migrated`);
        }

        // 执行回滚逻辑
        this.logger.info(`Rolling back component migration: ${componentName}`);
        
        // 移除迁移状态
        this.status.migratedComponents.splice(index, 1);
        
        this.logger.info(`Component migration rolled back: ${componentName}`);
    }

    /**
     * 优雅关闭
     */
    async shutdown(): Promise<void> {
        this.logger.info('Shutting down component decoupling system');

        // 清理事件总线
        if (this.eventBus) {
            this.eventBus.cleanup();
        }

        // 生成最终报告
        const finalStatus = this.getStatus();
        this.logger.info('Final component decoupling status', { metadata: finalStatus });

        this.isInitialized = false;
        this.logger.info('Component decoupling system shut down successfully');
    }
}

/**
 * 便捷的初始化函数
 */
export async function initializeComponentDecoupling(config?: ComponentDecouplingConfig): Promise<void> {
    const manager = ComponentDecouplingManager.getInstance();
    await manager.initialize(config);
}

/**
 * 获取组件解耦管理器
 */
export function getComponentDecouplingManager(): ComponentDecouplingManager {
    return ComponentDecouplingManager.getInstance();
}

/**
 * 获取事件总线实例
 */
export function getComponentEventBus(): ComponentEventBus {
    return ComponentDecouplingManager.getInstance().getEventBus();
}
